package org.viva.service.cms;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.viva.core.dao.BaseDAO;
import org.viva.entity.cms.Category;

@Service("categoryService")
public class CategoryService {

    @Resource
    private BaseDAO<Category> dao;

    public List<Category> getRoot() {
        return dao.find("from Category where pid is null order by sort");
    }

    public List<Category> getSelects() {
        List<Category> l = dao.find("from Category where pid is null order by sort");
        List<Category> list = new ArrayList<>();
        for (Category category : l) {
            add(list, category);
        }
        return list;
    }

    private void add(List<Category> list, Category category) {
        list.add(category);
        if (category.getChildren() != null) {
            for (Category c : category.getChildren()) {
                add(list, c);
            }
        }
    }

    public Category get(Long id) {
        return dao.get(Category.class, id);
    }

    public Category getByCode(String code) {
        return dao.get("from Category where code = ?", new String[] { code });
    }

    public void up(Category category) {
        Category c = dao.get(Category.class, category.getId());
        c.setName(category.getName());
        c.setPid(category.getPid());
        c.setSort(category.getSort());
        c.setCode(category.getCode());
        c.setAtp(category.getAtp());
        c.setCgtp(category.getCgtp());
        c.setMemo(category.getMemo());
    }

    public void add(Category category) {
        dao.saveOrUpdate(category);
    }

    public void del(Long id) {
        if (id == null) return;
        Category category = dao.get(Category.class, id);
        if (category == null) return;
        dao.delete(category);
    }

}
